<script lang="ts" setup>
import {ref,onMounted,provide,nextTick} from 'vue'
import {randomMath,randomMathNotSame} from "@/util/util";
import emitter from './util/mitt';
let audioList:string[] = [
    require('@/assets/mp3/happy.mp3'),
    require('@/assets/mp3/yihuik苡慧.mp3')
]
let playIndex = ref<number>(0) // 当前播放的下标
let audioSrc = ref<string>(audioList[playIndex.value])
let audio = ref()


let timeupdateHandler = (e:any) => {
  let {target} = e
  if(target){
    target.paused ? target.play() : null
  }
}


// playend 方法
let endedHandler = async function (){
  console.log('未切换前idx',playIndex.value)
  let r = randomMathNotSame(0,audioList.length-1,playIndex.value)
  console.log('no rpeate index生成idx',r)
  audio.value.src = audioList[r]
  playIndex.value = r
    try {
      await audio.value.play()
    }catch (e) {
      console.log('播放捕获错误',e)
    }
}

// 控制声音
let setAudioPlay = (play:boolean) => {
  if(!play) {
    audio.value.pause()
    audio.value.src = ''
  }else {
    audio.value.src = audioList[playIndex.value]
    audio.value.play()
  }
}

onMounted(() => {
  provide('audioDom',audio)
  emitter.on('*',(type,e:any) => {
    if(type == 'set-audio-play') {
      setAudioPlay(e)
    }
  })
})

</script>


<template>
  <div>
    <router-view></router-view>
    <audio class="cus-audio" ref="audio" @timeupdate="timeupdateHandler" @ended="endedHandler" style="display: none;" muted controls :src="audioSrc"></audio>
  </div>
</template>

<style lang="scss">
#app {
  width: 100%;
  height: 100vh;
}
</style>
